<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="utf-8">
  <title>Sign in &laquo; Admin</title>
  <link rel="stylesheet" href="/assets/vendors/bootstrap/css/bootstrap.css">
  <link rel="stylesheet" href="/assets/css/admin.css">
</head>

<body>
  <div class="login">
    <div class="login-wrap">
      <img class="avatar" src="/assets/img/default.png">
      <!-- 有错误信息时展示 -->
      <div id="errMsgBox" class="alert alert-danger" style="display: none;"></div>
      <div class="form-group">
        <label for="email" class="sr-only">邮箱</label>
        <input id="email" type="email" class="form-control" placeholder="邮箱" autofocus>
      </div>
      <div class="form-group">
        <label for="password" class="sr-only">密码</label>
        <input id="password" type="password" class="form-control" placeholder="密码">
      </div>
      <button class="btn btn-primary btn-block" id="loginBtn">登 录</button>
    </div>
  </div>

  <script src="/assets/vendors/jquery/jquery.min.js"></script>
  <script>
    $(() => {

      const $errMsgBox = $('#errMsgBox')
      const $loginBtn = $('#loginBtn')
      const $email = $('#email')
      const $password = $('#password')

      $loginBtn.click(() => {
        const email = $email.val().trim()
        const password = $password.val()
        console.log(email, password);

        if (email === '') {
          return $errMsgBox.show().html('请输入邮箱')
        }

        if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(email)) {
          return $errMsgBox.show().html('请输入正确的邮箱格式')
        }

        if (password === '') {
          return $errMsgBox.show().html('请输入密码')
        }

        // 可以包含数字字母下划线，6-16位
        if (!/^\w{6,16}$/.test(password)) {
          return $errMsgBox.show().html('密码不符合规则（由数字、字母、下划线组成，6-16位）')
        }

        $.ajax({
          type: 'POST',
          url: '/login',
          data: { email, password },
          // 只有当HTTP状态码为200时，才会进入这个success回调
          success(res) {
            // 将当前登录用户信息存储到sessionStorage中
            sessionStorage.setItem('curUser', JSON.stringify(res))
            location.href = '/admin/index.html'
          },
          // error并没有给我们转换JSON字符串
          error(xhr) {
            const res = JSON.parse(xhr.responseText)
            $errMsgBox.show().html(res.message)
          }
        })

      })

      $password.keyup(({ keyCode }) => {
        if (keyCode === 13) {
          $loginBtn.click()
        }
      })
    })
  </script>
</body>

</html>